package com.example.pcl.utils;

import com.example.pcl.exception.ObjectException;
import com.example.pcl.pojo.entity.Students;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelUtil {
    public static @NotNull List<Students> getStudentlist(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new ObjectException("Excel 文件中没有工作表！");
            }
            List<Students> students = new ArrayList<>();
            // 遍历行（跳过表头）
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) continue;

                Students student = new Students();

                // 解析每一列数据
                student.setStudentNumber(row.getCell(0).getStringCellValue()); // 学号
                student.setName(row.getCell(1).getStringCellValue());          // 姓名
                student.setGrade(row.getCell(2).getStringCellValue());         // 年级
                student.setCollege(row.getCell(3).getStringCellValue());       // 学院
                student.setMajor(row.getCell(4).getStringCellValue());         // 专业

                students.add(student);
            }
            return students;
        } catch (IOException e) {
            log.error("解析 Excel 文件失败: {}", e.getMessage(), e);
            throw new ObjectException("解析 Excel 文件失败！");
        }
    }


}